#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
重构后通信管理器的简单演示
展示队列和独立线程机制的使用
"""

import sys
import time
import threading
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel, QTextEdit
from PyQt6.QtCore import QTimer, pyqtSignal, QObject

# 添加src目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

try:
    from src.core.communication_manager_new import CommunicationManager
    print("✅ 成功导入重构后的通信管理器")
except ImportError as e:
    print(f"❌ 导入重构后的通信管理器失败: {e}")
    print("请确保已创建 communication_manager_new.py 文件")
    sys.exit(1)

class SimpleDemo(QObject):
    """简单演示类"""
    
    data_processed = pyqtSignal(str)
    status_updated = pyqtSignal(str)
    
    def __init__(self):
        super().__init__()
        self.comm_manager = None
        self.demo_running = False
        self.demo_thread = None
        self.data_count = 0
        
    def setup_demo(self):
        """设置演示环境"""
        try:
            print("🚀 正在设置通信管理器...")
            self.comm_manager = CommunicationManager()
            
            # 设置数据回调
            self.comm_manager.set_data_callback(self.on_data_processed)
            
            # 连接信号
            if self.comm_manager.data_processing_thread:
                self.comm_manager.data_processing_thread.data_processed.connect(self.on_data_processed)
                self.comm_manager.data_processing_thread.processing_error.connect(self.on_processing_error)
                self.comm_manager.data_processing_thread.processing_status.connect(self.on_processing_status)
                print("✅ 信号连接成功")
            
            self.status_updated.emit("通信管理器设置完成")
            print("✅ 通信管理器设置完成")
            return True
            
        except Exception as e:
            error_msg = f"设置通信管理器失败: {e}"
            self.status_updated.emit(error_msg)
            print(f"❌ {error_msg}")
            return False
    
    def on_data_processed(self, data):
        """数据处理完成回调"""
        try:
            self.data_count += 1
            data_str = f"📊 收到第 {self.data_count} 条处理后的数据: {data}"
            self.data_processed.emit(data_str)
            print(data_str)
        except Exception as e:
            error_msg = f"处理数据回调错误: {e}"
            self.data_processed.emit(error_msg)
            print(f"❌ {error_msg}")
    
    def on_processing_error(self, error_msg):
        """处理错误回调"""
        self.status_updated.emit(f"处理错误: {error_msg}")
        print(f"❌ 处理错误: {error_msg}")
    
    def on_processing_status(self, status_msg):
        """处理状态回调"""
        self.status_updated.emit(f"处理状态: {status_msg}")
        print(f"ℹ️ 处理状态: {status_msg}")
    
    def start_demo(self):
        """开始演示"""
        if not self.comm_manager:
            self.status_updated.emit("请先设置通信管理器")
            print("❌ 请先设置通信管理器")
            return
        
        print("🚀 开始演示...")
        self.demo_running = True
        self.demo_thread = threading.Thread(target=self._demo_data_generation)
        self.demo_thread.daemon = True
        self.demo_thread.start()
        self.status_updated.emit("演示已开始")
    
    def stop_demo(self):
        """停止演示"""
        print("⏹️ 停止演示...")
        self.demo_running = False
        if self.demo_thread:
            self.demo_thread.join(timeout=1.0)
        self.status_updated.emit("演示已停止")
    
    def _demo_data_generation(self):
        """演示数据生成线程"""
        try:
            count = 0
            print("📡 开始生成演示数据...")
            
            while self.demo_running:
                # 生成模拟的LIS协议数据
                test_data = self._generate_lis_data(count)
                
                # 添加到处理队列
                self.comm_manager.add_data_to_queue(
                    test_data,
                    "演示数据源",
                    "custom_lis",
                    f"DEMO_{count}"
                )
                
                count += 1
                time.sleep(0.2)  # 200ms间隔，模拟真实数据传输
                
                if count % 50 == 0:
                    status_msg = f"已生成 {count} 条演示数据"
                    self.status_updated.emit(status_msg)
                    print(f"📈 {status_msg}")
                
        except Exception as e:
            error_msg = f"演示数据生成错误: {e}"
            self.status_updated.emit(error_msg)
            print(f"❌ {error_msg}")
    
    def _generate_lis_data(self, count):
        """生成模拟的LIS协议数据"""
        # 模拟不同模式的LIS数据
        if count % 3 == 0:
            # 常规模式
            results = "HbA1a|5.2|HbA1b|0.8|HbF|0.5|LA1c|0.3|HbA1c|6.8|HbA0|87.4|eAG|7.8"
            mode = "常规模式"
        elif count % 3 == 1:
            # 变异/地贫模式
            results = "HbA1a|5.1|HbA1b|0.7|HbF|1.2|LA1c|0.4|HbA1c|6.5|p3|0.8|HbA0|85.3|A2|3.2|HbE|0.0|HbD|0.0|HbS|0.0|HbC|0.0|eAG|7.5"
            mode = "变异/地贫模式"
        else:
            # 快速变异模式
            results = "HbA1a|5.3|HbA1b|0.9|HbF|0.6|LA1c|0.2|HbA1c|6.9|p3|0.7|HbA0|87.0|v-win|0.8|eAG|7.9"
            mode = "快速变异模式"
        
        # 构建完整的LIS消息
        lis_message = f"""<TRANSMIT>
<M>LD600|SN001</M>
<I>sample|2025-01-27-14-30|SAMPLE_{count:04d}|SAMPLE_{count:04d}|RACK001|A01|血液</I>
<R>{results}</R>
<IMAGE>
<NAME>sample_{count:04d}.jpg</NAME>
<SIZE>1024</SIZE>
<DATA>FFD8FFE000104A46494600010101006000600000FFDB004300080606070605080707070909080A0C140D0C0B0B0C1912130F141D1A1F1E1D1A1C1C20242E2720222C231C1C2837292C30313434341F27393D38323C2E333432FFC0000B08001F000101011100FFC4001F0000010501010101010100000000000000000102030405060708090A0BFFC400B5100002010303020403050504040000017D01020300041105122131410613516107227114328191A1082342B1C11552D1F02433627282090A161718191A25262728292A3435363738393A434445464748494A535455565758595A636465666768696A737475767778797A838485868788898A92939495969798999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE1E2E3E4E5E6E7E8E9EAF1F2F3F4F5F6F7F8F9FAFFDA0008010100003F00</DATA>
</IMAGE>
</TRANSMIT>"""
        
        return lis_message.encode('utf-8')
    
    def get_queue_status(self):
        """获取队列状态"""
        if self.comm_manager:
            status = self.comm_manager.get_queue_status()
            status_str = f"队列状态: 大小={status.get('queue_size', 0)}, " \
                        f"已处理={status.get('processed_count', 0)}, " \
                        f"总消息={status.get('message_count', 0)}"
            self.status_updated.emit(status_str)
            print(f"📊 {status_str}")
        else:
            self.status_updated.emit("通信管理器未设置")
            print("❌ 通信管理器未设置")
    
    def clear_queue(self):
        """清空队列"""
        if self.comm_manager:
            self.comm_manager.clear_data_queue()
            self.status_updated.emit("队列已清空")
            print("🧹 队列已清空")
        else:
            self.status_updated.emit("通信管理器未设置")
            print("❌ 通信管理器未设置")
    
    def enable_processing(self, enabled=True):
        """启用/禁用数据处理"""
        if self.comm_manager:
            self.comm_manager.enable_data_processing(enabled)
            status = "启用" if enabled else "禁用"
            self.status_updated.emit(f"数据处理已{status}")
            print(f"✅ 数据处理已{status}")
        else:
            self.status_updated.emit("通信管理器未设置")
            print("❌ 通信管理器未设置")

class DemoWindow(QWidget):
    """演示窗口"""
    
    def __init__(self):
        super().__init__()
        self.demo = SimpleDemo()
        self.init_ui()
        self.setup_connections()
        
        # 定时器，用于更新状态
        self.status_timer = QTimer()
        self.status_timer.timeout.connect(self.update_status)
        self.status_timer.start(2000)  # 每2秒更新一次状态
        
        print("🎉 演示窗口已创建")
    
    def init_ui(self):
        """初始化界面"""
        self.setWindowTitle("通信管理器重构演示")
        self.setGeometry(100, 100, 900, 700)
        
        # 布局
        layout = QVBoxLayout(self)
        
        # 标题
        title = QLabel("🔧 通信管理器重构演示")
        title.setStyleSheet("font-size: 18px; font-weight: bold; margin: 10px;")
        layout.addWidget(title)
        
        # 说明
        description = QLabel("本演示展示重构后的通信管理器如何使用队列和独立线程处理数据，避免界面假死")
        description.setStyleSheet("margin: 5px; color: #666;")
        layout.addWidget(description)
        
        # 控制按钮
        self.setup_btn = QPushButton("🚀 设置通信管理器")
        self.start_btn = QPushButton("▶️ 开始演示")
        self.stop_btn = QPushButton("⏹️ 停止演示")
        self.status_btn = QPushButton("📊 获取队列状态")
        self.clear_btn = QPushButton("🧹 清空队列")
        self.enable_btn = QPushButton("✅ 启用数据处理")
        self.disable_btn = QPushButton("❌ 禁用数据处理")
        
        # 状态标签
        self.status_label = QLabel("状态: 未初始化")
        self.status_label.setStyleSheet("font-weight: bold; color: #333; margin: 10px;")
        
        # 日志显示
        log_label = QLabel("📝 运行日志:")
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        self.log_text.setMaximumHeight(300)
        
        # 添加到布局
        layout.addWidget(self.setup_btn)
        layout.addWidget(self.start_btn)
        layout.addWidget(self.stop_btn)
        layout.addWidget(self.status_btn)
        layout.addWidget(self.clear_btn)
        layout.addWidget(self.enable_btn)
        layout.addWidget(self.disable_btn)
        layout.addWidget(self.status_label)
        layout.addWidget(log_label)
        layout.addWidget(self.log_text)
        
        # 初始按钮状态
        self.start_btn.setEnabled(False)
        self.stop_btn.setEnabled(False)
        self.status_btn.setEnabled(False)
        self.clear_btn.setEnabled(False)
        self.enable_btn.setEnabled(False)
        self.disable_btn.setEnabled(False)
        
        print("🎨 界面初始化完成")
    
    def setup_connections(self):
        """设置信号连接"""
        self.setup_btn.clicked.connect(self.setup_demo)
        self.start_btn.clicked.connect(self.start_demo)
        self.stop_btn.clicked.connect(self.stop_demo)
        self.status_btn.clicked.connect(self.get_queue_status)
        self.clear_btn.clicked.connect(self.clear_queue)
        self.enable_btn.clicked.connect(self.enable_processing)
        self.disable_btn.clicked.connect(self.disable_processing)
        
        # 连接演示信号
        self.demo.data_processed.connect(self.on_data_processed)
        self.demo.status_updated.connect(self.on_status_updated)
        
        print("🔗 信号连接完成")
    
    def setup_demo(self):
        """设置演示"""
        if self.demo.setup_demo():
            self.setup_btn.setEnabled(False)
            self.start_btn.setEnabled(True)
            self.status_btn.setEnabled(True)
            self.clear_btn.setEnabled(True)
            self.enable_btn.setEnabled(True)
            self.disable_btn.setEnabled(True)
            self.log_message("✅ 通信管理器设置成功")
        else:
            self.log_message("❌ 通信管理器设置失败")
    
    def start_demo(self):
        """开始演示"""
        self.demo.start_demo()
        self.start_btn.setEnabled(False)
        self.stop_btn.setEnabled(True)
        self.log_message("🚀 演示已开始")
    
    def stop_demo(self):
        """停止演示"""
        self.demo.stop_demo()
        self.start_btn.setEnabled(True)
        self.stop_btn.setEnabled(False)
        self.log_message("⏹️ 演示已停止")
    
    def get_queue_status(self):
        """获取队列状态"""
        self.demo.get_queue_status()
    
    def clear_queue(self):
        """清空队列"""
        self.demo.clear_queue()
    
    def enable_processing(self):
        """启用数据处理"""
        self.demo.enable_processing(True)
    
    def disable_processing(self):
        """禁用数据处理"""
        self.demo.enable_processing(False)
    
    def on_data_processed(self, data_str):
        """数据接收回调"""
        self.log_message(data_str)
    
    def on_status_updated(self, status_str):
        """状态更新回调"""
        self.status_label.setText(f"状态: {status_str}")
        self.log_message(status_str)
    
    def log_message(self, message):
        """记录日志消息"""
        timestamp = time.strftime("%H:%M:%S")
        self.log_text.append(f"[{timestamp}] {message}")
        
        # 限制日志行数
        lines = self.log_text.toPlainText().split('\n')
        if len(lines) > 500:
            self.log_text.setPlainText('\n'.join(lines[-250:]))
    
    def update_status(self):
        """定时更新状态"""
        if self.demo.comm_manager and self.demo.demo_running:
            self.demo.get_queue_status()
    
    def closeEvent(self, event):
        """窗口关闭事件"""
        print("👋 正在关闭演示窗口...")
        self.demo.stop_demo()
        if self.demo.comm_manager:
            self.demo.comm_manager.stop_all()
            print("🛑 所有通信和数据处理已停止")
        event.accept()

def main():
    """主函数"""
    print("🚀 启动通信管理器重构演示...")
    
    app = QApplication(sys.argv)
    
    # 创建演示窗口
    window = DemoWindow()
    window.show()
    
    print("🎉 演示窗口已显示，开始演示...")
    
    # 运行应用
    sys.exit(app.exec())

if __name__ == "__main__":
    main()
